cmake_minimum_required(VERSION 3.0)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules")

option(SSL_SUPPORT "SSL support" ON)
option(USE_OPENSSL "Force select OpenSSL" OFF)
option(USE_WOLFSSL "Force select WolfSSL(CyaSSL)" OFF)
option(USE_MBEDTLS "Force select MbedTLS(PolarSSL)" OFF)

if (NOT SSL_SUPPORT)
    return()
endif()


find_package(PkgConfig QUIET)

find_package(OpenSSL)

if (NOT OPENSSL_FOUND)
    pkg_check_modules(OPENSSL openssl)
endif()

find_package(WolfSSL)
find_package(MbedTLS)
find_package(ZLIB)

if(USE_OPENSSL)
    if (NOT OPENSSL_FOUND)
        message(FATAL_ERROR "Force select OpenSSL, but not found it")
    endif()
elseif(USE_WOLFSSL)
    if (NOT WOLFSSL_FOUND)
        message(FATAL_ERROR "Force select WolfSSL(CyaSSL), but not found it")
    endif()
elseif(USE_MBEDTLS)
    if (NOT MBEDTLS_FOUND)
        message(FATAL_ERROR "Force select MbedTLS(PolarSSL), but not found it")
    endif()
elseif(OPENSSL_FOUND)
    set(USE_OPENSSL ON)
elseif(WOLFSSL_FOUND)
    set(USE_WOLFSSL ON)
elseif(MBEDTLS_FOUND)
    set(USE_MBEDTLS ON)
else()
    message(WARNING "No available SSL libraries found")
endif()

if(USE_OPENSSL OR USE_WOLFSSL OR USE_MBEDTLS)
    set(SSL_SUPPORT ON)

    if(USE_OPENSSL)
        set(SSL_NAME "OpenSSL")
        set(SSL_SRC ${CMAKE_CURRENT_SOURCE_DIR}/openssl.c)
        set(SSL_INC ${OPENSSL_INCLUDE_DIR})
        set(SSL_LIBS ${OPENSSL_LIBRARIES})
        set(SSL_DEFINE HAVE_OPENSSL)
    elseif(USE_WOLFSSL)
        set(SSL_NAME "WolfSSL(CyaSSL)")
        set(SSL_SRC ${CMAKE_CURRENT_SOURCE_DIR}/openssl.c)
        set(SSL_INC ${WOLFSSL_INCLUDE_DIR})
        set(SSL_LIBS ${WOLFSSL_LIBRARIES})
        set(SSL_DEFINE HAVE_WOLFSSL)
    elseif(USE_MBEDTLS)
        set(SSL_NAME "MbedTLS(PolarSSL)")
        set(SSL_SRC ${CMAKE_CURRENT_SOURCE_DIR}/mbedtls.c)
        set(SSL_INC ${MBEDTLS_INCLUDE_DIR})
        set(SSL_LIBS ${MBEDTLS_LIBRARIES})
        if(ZLIB_FOUND)
            list(APPEND SSL_LIBS ${ZLIB_LIBRARIES})
        endif()
        set(SSL_DEFINE HAVE_MBEDTLS)
    endif()
endif()

if(SSL_SUPPORT)
    message(STATUS "Select ${SSL_NAME} as the SSL backend")

    add_library(xssl STATIC ${SSL_SRC})
    target_compile_definitions(xssl PRIVATE ${SSL_DEFINE})
    target_compile_options(xssl PRIVATE -O -Wall -Werror --std=gnu99 -fPIC)
    target_include_directories(xssl PRIVATE ${SSL_INC})
    target_link_libraries(xssl PRIVATE ${SSL_LIBS})

    set(SSL_SUPPORT ${SSL_SUPPORT} PARENT_SCOPE)
    set(SSL_TARGET xssl PARENT_SCOPE)

    set(SSL_SRC ${SSL_SRC} PARENT_SCOPE)
    set(SSL_INC ${SSL_INC} PARENT_SCOPE)
    set(SSL_LIBS ${SSL_LIBS} PARENT_SCOPE)
    set(SSL_DEFINE ${SSL_DEFINE} PARENT_SCOPE)
endif()
